import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Standardize;
import weka.filters.unsupervised.attribute.PrincipalComponents;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import java.io.File;
import java.io.IOException;

public class 主成分 {

    public static void main(String[] args) throws Exception {
        // 读取CSV文件
        DataSource dataSource = new DataSource("D:\\Marketing Campaign\\填充后的数据集.csv");
        Instances data = dataSource.getDataSet();
        data.setClassIndex(data.numAttributes() - 1); // 设置最后一列为类别属性（如果有的话）

        // 选择特征
        String[] features = {"Year_Birth", "Education", "Kidhome", "Teenhome", "Income"};
        Instances selectedData = selectFeatures(data, features);

        // 标准化数据
        Standardize standardize = new Standardize();
        standardize.setInputFormat(selectedData);
        Instances dataScaled = Filter.useFilter(selectedData, standardize);

        // 进行PCA
        PrincipalComponents pca = new PrincipalComponents();
        pca.setMaximumAttributesToSelect(2); // 选择主成分数
        pca.setInputFormat(dataScaled);
        Instances pcaData = Filter.useFilter(dataScaled, pca);

        // 查看方差解释比例
        double[] eigenValues = pca.getEigenValues();
        System.out.println("方差解释比例:");
        for (int i = 0; i < eigenValues.length; i++) {
            System.out.println("PC" + (i + 1) + ": " + eigenValues[i]);
        }

        // 可视化PCA结果
        XYSeries series = new XYSeries("PCA Data");
        for (int i = 0; i < pcaData.numInstances(); i++) {
            double pc1 = pcaData.instance(i).value(0);
            double pc2 = pcaData.instance(i).value(1);
            series.add(pc1, pc2);
        }

        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(series);

        JFreeChart chart = ChartFactory.createXYLineChart(
                "PCA of Selected Features",
                "主成分1",
                "主成分2",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        ChartFrame frame = new ChartFrame("PCA Chart", chart);
        frame.pack();
        frame.setVisible(true);
    }

    private static Instances selectFeatures(Instances data, String[] features) throws IOException {
        Instances selectedData = new Instances(data, 0);
        for (String feature : features) {
            int index = data.attribute(feature).index();
            selectedData.insertAttributeAt(index, data.attribute(feature));
        }
        for (int i = 0; i < data.numInstances(); i++) {
            selectedData.add(data.instance(i));
        }
        return selectedData;
    }
}